<template>
  <div class="data-list">
    <transition-group name="deletable-item" tag="div">
      <div class="data" v-for="type in types" :key="type.id">
        <div>
          <span class="label">类名</span>
          <span class="value">{{ type.name }}</span>
        </div>
        <div>
          <span class="label">单位</span>
          <span class="value">{{ type.unit }}</span>
        </div>
        <i @click="deleteTypeByID(type.id)" class="del-btn el-icon-error" />
      </div>
    </transition-group>
  </div>
  <div class="plus-btn" @click="changeVisible(true)">
    <i class="el-icon-circle-plus" />
  </div>
  <el-dialog v-model="visible" width="90%">
    <el-form :model="typeForm" :rules="rules" ref="typeFormRef">
      <el-form-item label="类型名称" prop="name">
        <el-input v-model="typeForm.name" maxlength="5"></el-input>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="typeForm.unit" maxlength="5" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitType">提交</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { onMounted, reactive, ref, Ref } from "vue";
import { listTypes, addType, delType, Type } from "/@/util/api";
export default {
  name: "TypeManager",
  setup(props, context) {
    // 页面展示类型逻辑
    let types: Ref<Array<Type>> = ref([]);
    function getAllTypes() {
      listTypes().then((res) => {
        if (res.code === 0) {
          types.value = res.data;
          window.sessionStorage.setItem("all-types", JSON.stringify(res.data));
        }
      });
    }
    onMounted(() => {
      getAllTypes();
    });

    // 删除类型
    function deleteTypeByID(typeID: number) {
      delType(typeID).then((res) => {
        if (res.code === 0) {
          getAllTypes();
        }
      });
    }

    // 弹窗显示逻辑
    let visible = ref(false);
    function changeVisible(v: boolean) {
      visible.value = v;
    }

    // 提交表单逻辑
    let typeForm = reactive({ name: "", unit: "" });
    let rules = {
      name: [{ required: true, message: "请输入类型名", trigger: "blur" }],
      unit: [{ required: true, message: "请输入类型单位", trigger: "blur" }],
    };
    let typeFormRef = ref(null);
    function submitType() {
      (typeFormRef.value as any).validate((valid: any) => {
        if (valid) {
          addType(typeForm).then((res) => {
            if (res.code === 0) {
              changeVisible(false);
              getAllTypes();
              (typeFormRef.value as any).resetFields();
            }
          });
        } else {
          return false;
        }
      });
    }

    return {
      types,
      submitType,
      typeFormRef,
      visible,
      changeVisible,
      rules,
      deleteTypeByID,
      typeForm,
    };
  },
};
</script>
<style lang="scss" scoped>
@import "../util/util.scss";
.plus-btn {
  @include plus-btn;
}

</style>